package svnserver.repository.git;

import org.eclipse.jgit.lib.Repository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import svnserver.repository.VcsBranchMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class GitBranchMode implements VcsBranchMode {
  private static final Logger log = LoggerFactory.getLogger(GitBranchMode.class);
  final private Repository repository;

  public static String getDefaultBranchName(@NotNull String gitDir) {
    String head = gitDir + "/HEAD";
    File file = new File(head);
    if (!file.exists() || file.isDirectory())
      return null;
    FileReader fr;
    try {
      fr = new FileReader(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }
    String line;
    BufferedReader br = new BufferedReader(fr);
    try {
      line = br.readLine();
      br.close();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

    /****if(line.split(""))
    * ref: refs/heads/master
     * ref: refs/heads/develop
     *
     * test get default branch success, test OK.
    ****/
    if (line.length() < "ref: refs/heads/".length())
      return null;
    return line.substring("ref: refs/heads/".length());
  }

  ////
  GitBranchMode(@NotNull Repository repository) {
    this.repository = repository;
  }

  @Nullable
  @Override
  public String getDefaultBranch() {
    ///
    try {
      final String branch = repository.getBranch();
      return branch;
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }

  @Override
  public String TranslateSubversionBranchName(@NotNull String svnBranch) {
    if (svnBranch.equals("trunk")) {
      return getDefaultBranch();
    }
    return svnBranch;
  }

  @Override
  public String BranchNameRestore(@NotNull String gitBranch) {
    if (gitBranch.equals(getDefaultBranch()))
      return "trunk";
    return gitBranch;
  }
}
